#!/usr/bin env python3
# -*- coding: utf-8 -*-
# Filename: check_mail.py
# To check my Mail status in command line

from urllib import request, parse
import json
import random
import time


def check_mails(mail_id):
    """Return mailId info"""

    # http://www.kuaidi100.com/autonumber/autoComNum
    req_url = "http://www.kuaidi100.com/autonumber/autoComNum"
    req = request.Request(req_url)
    # header 1
    req.add_header('Host', 'www.kuaidi100.com')
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:55.0) Gecko/20100101 Firefox/55.0')
    req.add_header('Referer', 'http://www.kuaidi100.com/?from=openv')
    # post data
    post_data = parse.urlencode([
        ('text', mail_id)
    ])
    # to get the com code
    coms = []

    with request.urlopen(req, data=post_data.encode('utf-8')) as f:
        data1 = f.read().decode('utf-8')
        data2 = json.loads(data1)
        comData = data2['auto']
    for x in comData:
        coms.append(x['comCode'])
    # no need to check further if com is None
    if coms is None:
        return None

    for i in coms:
        # request2 post data
        post_data2 = parse.urlencode([
            ('type', str(i)),
            ('postid', str(mail_id)),
            ('id', '1'),
            ('valicode', ''),
            ('temp', str(random.random())[0:18])
        ])
        # request2 and header info
        req_url2 = "http://www.kuaidi100.com/query"
        req_2 = request.Request(req_url2)

        req_2.add_header('Host', 'www.kuaidi100.com')
        req_2.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:55.0) Gecko/20100101 Firefox/55.0')
        req_2.add_header('Accept', '*/*')
        req_2.add_header('Accept-Language', 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3')
        req_2.add_header('Referer', 'http://www.kuaidi100.com/?from=openv')
        req_2.add_header('Connection', 'keep-alive')

        contents = None
        ori_data = None
        with request.urlopen(req_2, data=post_data2.encode('utf-8')) as f:
            ori_data = json.loads(f.read())
            contents = ori_data['data']

        # content is a list, which contain a lots of json messages for mail
        if contents:
            return contents

    # empty response
    return None


"""
if __name__ == '__main__':

    print("查询快递信息：")
    print("我的快递单号：{0}".format(3338076907949))
    ori_data = 3338076907949
    mailId = 0
    flag = True
    while flag:
        print()
        print("你想用我的快递单号吗yes/no?")
        fl = input("y/n ?: ")
        if fl == 'y' or fl == 'yes':
            mailId = ori_data
            flag = False
        else:
            print("在data.txt中更新你的单号吧！")
            print("更新了就yes/y继续")
            res = input()
            if res == 'yes' or res == 'y':
                flag = False

    mails = []
    with open('data.txt', 'rt') as f:
        for dial in f:
            # the .strip() will strip the \r \n \t ' '
            if dial.strip() != '':
                mails.append(dial.strip())

    mails.append(ori_data)
    for x in mails:
        print("你的单号是：%s" % x)

    for mailId in mails:

        post_data_step1 = parse.urlencode([
            ('text', mailId)
        ])

        # http://www.kuaidi100.com/autonumber/autoComNum
        req = request.Request('http://www.kuaidi100.com/autonumber/autoComNum')
        req.add_header('Host', 'www.kuaidi100.com')
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:55.0) Gecko/20100101 Firefox/55.0')
        req.add_header('Referer', 'http://www.kuaidi100.com/?from=openv')
        # req.add_header('Connection', 'keep-alive')
        comCode_li = []
        jsonObj = {}

        # get_comCode
        with request.urlopen(req, data=post_data_step1.encode('utf-8')) as f:
            # print('Status: ', f.status, f.reason)
            # for k, v in f.getheaders():
            #     print('%s %s' % (k, v))
            data = f.read().decode('utf-8')
            data1 = json.loads(data)
            auto = data1['auto']
            for i in auto:
                jsonObj = i
                comCode_li.append(jsonObj['comCode'])

        # TODO: implement the second part.
        # print(comCode_li)
        # http://www.kuaidi100.com/query

        # get_mailMessage according to the comCode
        for i in comCode_li:
            post_data_step2 = parse.urlencode([
                ('type', str(i)),
                ('postid', str(mailId)),
                ('id', '1'),
                ('valicode', ''),
                ('temp', str(random.random())[0:18])
            ])
            req_2 = request.Request('http://www.kuaidi100.com/query')
            req_2.add_header('Host', 'www.kuaidi100.com')
            req_2.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:55.0) Gecko/20100101 Firefox/55.0')
            req_2.add_header('Accept', '*/*')
            req_2.add_header('Accept-Language', 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3')
            req_2.add_header('Referer', 'http://www.kuaidi100.com/?from=openv')
            req_2.add_header('Connection', 'keep-alive')
            with request.urlopen(req_2, data=post_data_step2.encode('utf-8')) as f:
                dataTotal = f.read()
                # print('Status', f.status, f.reason)
                data1 = dataTotal.decode('utf-8')
                data = json.loads(data1)
                contents = data['data']
            print("订单号：%s" % mailId)
            time.sleep(1)
            print(contents)
            for x in reversed(contents):
                print(x['time'], end='----------->')
                print(x['context'], end='\n')
                time.sleep(0.5)

            if contents:
                print("你的%s快递还没有消息哦！" % i)
            print()

"""
